package com.gzs.space.aop;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
@Slf4j
public class WebLogAspect {
    // 以 controller 包下定义的所有请求为切入点
    @Pointcut("execution(public * com.gzs.space.controller..*.*(..))")
    public void webLog() {}
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {

        // 开始打印请求日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();


        // 打印请求相关参数
        log.info("========================================== Start ==========================================");
        // 打印请求 url
        log.info("请求地址        : {}", request.getRequestURL().toString());
        // 打印 Http method
        log.info("请求方式        : {}", request.getMethod());
        // 打印调用 controller 的全路径以及执行方法
        log.info("请求方法所在路径 : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());

        ParameterNameDiscoverer pnd = new DefaultParameterNameDiscoverer();
        String[] keys = pnd.getParameterNames(method);
        Object[] values = joinPoint.getArgs();
        Map<String, Object> paramsMap = new HashMap<>();
        for (int i = 0; i < keys.length; i++) {
            paramsMap.put(keys[i],values[i]);
        }
        // 打印请求入参
        log.info("请求参数        : {}", new Gson().toJson(paramsMap));

    }

    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();

        Object result = proceedingJoinPoint.proceed();
        // 打印出参
        log.info("响应参数        : {}", new Gson().toJson(result));
        // 执行耗时
        log.info("响应时间        : {} ms", System.currentTimeMillis() - startTime);
        return result;
    }

    @After("webLog()")
    public void doAfter() throws Throwable {
        log.info("=========================================== End ===========================================");
        // 每个请求之间空一行
        log.info("");
    }
}